#include "ADC.h"
#include "delay.h"
#include "usart.h"


uint16_t adcData[ADC_CH_SIZE];


void DMA_Init(void)
{
   /* DMA Configure */
    DMA_Config_T dmaConfig;

    /* Enable DMA clock */
    RCM_EnableAHBPeriphClock(RCM_AHB_PERIPH_DMA1);

    /* Set Peripheral Address */
    dmaConfig.peripheralAddress = ADC_DR_ADDR;
    /* Set memory Address */
    dmaConfig.memoryAddress = (uint32_t)&adcData;
    /* read from peripheral */
    dmaConfig.direction = DMA_DIR_PERIPHERAL;
    /* size of buffer*/
    dmaConfig.bufferSize = ADC_CH_SIZE;
    /* Disable Peripheral Address increase */
    dmaConfig.peripheralInc = DMA_PERIPHERAL_INC_DISABLE;
    /* Enable Memory Address increase */
    dmaConfig.memoryInc = DMA_MEMORY_INC_ENABLE;
    /* Set peripheral Data Size */
    dmaConfig.peripheralDataSize = DMA_PERIPHERAL_DATASIZE_HALFWORD;
    /* set memory Data Size */
    dmaConfig.memoryDataSize = DMA_MEMORY_DATASIZE_HALFWORD;
    /* Reset Circular Mode */
    dmaConfig.circular = DMA_CIRCULAR_ENABLE;
    /* Disable M2M */
    dmaConfig.memoryTomemory = DMA_M2M_DISABLE;
    /* set priority */
    dmaConfig.priority = DMA_PRIORITY_LEVEL_HIGHT;

    DMA_Config(DMA1_CHANNEL_1, &dmaConfig);

    DMA_Enable(DMA1_CHANNEL_1);
}



void ADC_Init(void)
{
		GPIO_Config_T gpioConfig;
    ADC_Config_T  adcConfig;

    /* RCM Enable */
    RCM_EnableAHBPeriphClock(RCM_AHB_PERIPH_GPIOA);  //********端口号*******
    RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_ADC1);
    RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_SYSCFG);

    /* GPIO Configuration */
    gpioConfig.pin = GPIO_PIN_0 | GPIO_PIN_7;  //引脚号
    gpioConfig.mode = GPIO_MODE_AN;
    gpioConfig.pupd = GPIO_PUPD_NO;
    GPIO_Config(GPIOA, &gpioConfig);  //端口号

    /* ADC Configuration */
    ADC_Reset();
    ADC_ConfigStructInit(&adcConfig);

    /* Set resolution*/
    adcConfig.resolution = ADC_RESOLUTION_12B;   //设置分辨率
    /* Set dataAlign */
    adcConfig.dataAlign  = ADC_DATA_ALIGN_RIGHT;  //数据对齐  右对齐
    /* Set scanDir */
    adcConfig.scanDir    = ADC_SCAN_DIR_UPWARD;  //扫描
    /* Set convMode continous */
    adcConfig.convMode   = ADC_CONVERSION_CONTINUOUS;  //连续模式
    /* Set extTrigConv */
    adcConfig.extTrigConv  = ADC_EXT_TRIG_CONV_TRG0;
    /* Set TrigEdge */
    adcConfig.extTrigEdge    = ADC_EXT_TRIG_EDGE_NONE;  //触发方式无外部触发
		
//		adcConfig.extTrigEdge    = ADC_EXT_TRIG_EDGE_ALL;
		
    ADC_Config(&adcConfig);
		
		ADC_ConfigChannel(ADC_CHANNEL_0, ADC_SAMPLE_TIME_239_5);
    ADC_ConfigChannel(ADC_CHANNEL_7, ADC_SAMPLE_TIME_239_5); //设置通道
			
		DMA_Init();
			
		ADC_ReadCalibrationFactor();   //校准
		ADC_EnableDMA();
		ADC_DMARequestMode(ADC_DMA_MODE_CIRCULAR);
		ADC_Enable();   //使能

}

void ADC_MultiChannelPolling(void)
{
    float voltage;
    uint8_t index;

    for (index = 0; index < ADC_CH_SIZE; index++)
    {
        voltage = (adcData[index] * 3.3) / 4095.0;

        printf("ADC CH[%d] voltage = %.3f V\r\n", index, voltage);
    }
    printf("\r\n");
}




